package com.sphd.emanu.fragment.goods;


import android.content.Intent;
import android.graphics.Color;
import android.graphics.drawable.ColorDrawable;
import android.os.Bundle;
import android.support.v4.widget.SwipeRefreshLayout;
import android.support.v7.app.AlertDialog;
import android.support.v7.widget.RecyclerView;
import android.view.View;
import android.widget.ArrayAdapter;
import android.widget.ListView;
import android.widget.PopupWindow;
import android.widget.TextView;
import android.view.ViewGroup.LayoutParams;

import com.chad.library.adapter.base.BaseQuickAdapter;
import com.chad.library.adapter.base.listener.OnItemClickListener;
import com.github.yoojia.inputs.AndroidNextInputs;
import com.github.yoojia.inputs.StaticScheme;
import com.rengwuxian.materialedittext.MaterialEditText;
import com.sphd.emanu.R;
import com.sphd.emanu.activity.commoditypvsum.CommodityPvSumActivity;
import com.sphd.emanu.adapter.GoodsFragmentAdapter;
import com.sphd.emanu.config.Constant;
import com.sphd.emanu.mvp.MVPBaseFragment;
import com.sphd.emanu.permission.Moudle;
import com.sphd.emanu.pojo.goods.Category;
import com.sphd.emanu.pojo.goods.Commodity;
import com.sphd.emanu.pojo.login.User;
import com.sphd.emanu.pojo.material.CommodityAndCategory;
import com.sphd.emanu.utils.PermissionConfig;
import com.wzutils.L;
import com.wzutils.ScreenUtils;

import java.util.ArrayList;
import java.util.List;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import butterknife.Unbinder;


/**
 * 库房-----商品库存
 *
 * @Author Hu
 * @Time 2017/5/25 -- 16:01.
 * @Email 87683202@qq.com
 */
public class GoodsFragment extends MVPBaseFragment<GoodsContract.View, GoodsPresenter> implements GoodsContract.View, BaseQuickAdapter.RequestLoadMoreListener {

    @BindView(R.id.classify_name)
    TextView classifyName;
    @BindView(R.id.auto_orderby)
    TextView autoOrderby;
    @BindView(R.id.my_recycler)
    RecyclerView myRecycler;
    @BindView(R.id.my_swf)
    SwipeRefreshLayout mySwf;
    Unbinder unbinder;
    List<Category> categoryList;
    List<String> stringList;
    List<String> categoryString;
    List<String> sortString;
    Bundle bundle;
    User user;
    Integer status = 0, curpage = 1, pageno = 10;
    //status,curpage,当前第几页pageno,一页多少条
    // status 0默认排序, 1当前库存高到低,2当前库存低到高,3日点击次数高到低,4日点击次数低到高
    View popupView;
    ListView lsvMore;
    ArrayAdapter arrayAdapter;
    PopupWindow popupWindow;
    int type = 0;
    Integer catecoryType = 0;
    GoodsFragmentAdapter goodsFragmentAdapter;
    Intent intent;
    boolean isCanDo;
    List<Moudle> moudles;

    @Override
    protected int getLayoutId() {
        return R.layout.fragment_goods;
    }

    @Override
    protected void initView() {
        stringList = new ArrayList<>();
        unbinder = ButterKnife.bind(this, rootView);
        intent = new Intent();
        bundle = getArguments();
        user = (User) bundle.getSerializable(Constant.USER_ENTITY);
        moudles = (List<Moudle>) bundle.getSerializable(Constant.PERMISSION_LIST);
        isCanDo = isCanDo(moudles, PermissionConfig.MENU_STOREHOUSE_8);
        setRefresh(mySwf);
        initSort();
        initPop();
        initEvent();
        initAdapter();
        setUserVisibleHint(true);

    }

    private void initAdapter() {
        setRecy(myRecycler);
        goodsFragmentAdapter = new GoodsFragmentAdapter(R.layout.item_fragment_goods, new ArrayList<Commodity>());
        goodsFragmentAdapter.setOnLoadMoreListener(this, myRecycler);
       goodsFragmentAdapter.setEmptyView(emptyView);
        goodsFragmentAdapter.openLoadAnimation(BaseQuickAdapter.SLIDEIN_LEFT);
        myRecycler.setAdapter(goodsFragmentAdapter);

    }

    private void initSort() {
        //默认排序, 1当前库存高到低,2当前库存低到高,3日点击次数高到低,4日点击次数低到高
        sortString = new ArrayList<>();
        sortString.add("智能排序");
        sortString.add("当前库存由高到低");
        sortString.add("当前库存由低到高");
        sortString.add("日点击次数由高到低");
        sortString.add("日点击次数由低到高");

    }

    private void initEvent() {
        mySwf.setOnRefreshListener(() -> {
            curpage = 1;
            if ("全部".equals(classifyName.getText().toString().trim())) {
                addData();
            } else {
                addDataByCategory();
            }

        });
        myRecycler.addOnItemTouchListener(new OnItemClickListener() {
            @Override
            public void onSimpleItemClick(BaseQuickAdapter adapter, View view, int position) {

            }


            @Override
            public void onItemChildClick(BaseQuickAdapter adapter, View view, int position) {
                super.onItemChildClick(adapter, view, position);
                Commodity commodity = (Commodity) adapter.getItem(position);
                switch (view.getId()) {
                    case R.id.layout_commdity:
                        bundle.putSerializable(Constant.COMMODITY, commodity);
                        intent.putExtras(bundle);
                        intent.setClass(context, CommodityPvSumActivity.class);
                        startActivity(intent);
                        break;
                    case R.id.layout_stronge_set:
                        if (isCanDo)
                            addAndEdit(commodity.getName(), String.valueOf(commodity.getReserveStock()), commodity.getId(), position);
                        break;
                }
            }
        });


        lsvMore.setOnItemClickListener((parent, view, position, id) -> {
            curpage = 1;
            popupWindow.dismiss();
            if (type == 0) {
                if ("全部".equals(stringList.get(position))) {
                    addData();
                } else {
                    catecoryType = position - 1;
                    addDataByCategory();
                }
                classifyName.setText(stringList.get(position));
            } else if (type == 1) {
                status = position;
                autoOrderby.setText(sortString.get(position));
                if ("全部".equals(classifyName.getText().toString().trim())) {
                    addData();
                } else {
                    addDataByCategory();
                }
            }
        });
    }

    private void addDataByCategory() {
        showProgressDialog();
        mPresenter.commodityStockByCategory(categoryList.get(catecoryType).getId(), status, curpage, pageno);
    }

    private void initPop() {
        // TODO: 2016/5/17 构建一个popupwindow的布局
        popupView = View.inflate(context, R.layout.popup_windows, null);
        // TODO: 2016/5/17 为了演示效果，简单的设置了一些数据，实际中大家自己设置数据即可，相信大家都会。
        lsvMore = (ListView) popupView.findViewById(R.id.lsvMore);
        arrayAdapter = new ArrayAdapter<String>(context, R.layout.item_text_center, stringList);
        lsvMore.setAdapter(arrayAdapter);
        popupWindow = new PopupWindow(popupView,
                ScreenUtils.getScreenWidth(context) / 2, LayoutParams.WRAP_CONTENT, true);
        popupWindow.setTouchable(true);
        // TODO: 2016/5/17 设置动画
        popupWindow.setAnimationStyle(R.style.popup_window_anim);
        // TODO: 2016/5/17 设置背景颜色
        popupWindow.setBackgroundDrawable(new ColorDrawable(Color.parseColor("#F8F8F8")));
        // TODO: 2016/5/17 设置可以获取焦点
        popupWindow.setFocusable(true);
        // TODO: 2016/5/17 设置可以触摸弹出框以外的区域
        popupWindow.setOutsideTouchable(true);
        // TODO：更新popupwindow的状态
        popupWindow.update();
        // TODO: 2016/5/17 以下拉的方式显示，并且可以设置显示的位置
//        popupWindow.showAsDropDown(textView);

    }

    @Override
    protected void initData() {
        addData();
    }

    private void addData() {
        showProgressDialog();
        mPresenter.commodityStock(user.getOid(), status, curpage, pageno);
    }

    @Override
    public void setBeanList(List<Commodity> commodityList) {
        dissProgressDialog();
        addList(commodityList);

    }

    private void addList(List<Commodity> commodityList) {
        if (curpage == 1) {
            goodsFragmentAdapter.setNewData(commodityList);
        } else {
            goodsFragmentAdapter.addData(commodityList);
        }

        if (commodityList.size() != pageno) {
            goodsFragmentAdapter.loadMoreEnd(false);
        } else {
            goodsFragmentAdapter.loadMoreComplete();
        }
    }

    @Override
    public void setRes(int res, int pos, int resrverStock, AlertDialog alertDialog) {
        dissProgressDialog();
        if (res == 1) {
            toast("修改成功");
            goodsFragmentAdapter.getData().get(pos).setReserveStock((long) resrverStock);
            goodsFragmentAdapter.notifyItemChanged(pos);
            alertDialog.dismiss();
        } else {
            toast("修改失败，请重试！");
        }
    }

    private void addAndEdit(String title, String classfy, final int id, int pos) {
        View view = View.inflate(context, R.layout.dialog_edit, null);
        final MaterialEditText materialEditText = (MaterialEditText) view.findViewById(R.id.my_edit);
        materialEditText.setHint("请输入预设库存量");
        materialEditText.setText(classfy);

        final AlertDialog alertDialog = getDialogBuilder(view, title, "确定", "取消");
        final AndroidNextInputs androidNextInputs = new AndroidNextInputs();
        androidNextInputs.add(materialEditText, StaticScheme.Required(),
                StaticScheme.NotBlank(), StaticScheme.Numeric());
        alertDialog.show();
        alertDialog.getButton(AlertDialog.BUTTON_POSITIVE).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (androidNextInputs.test()) {
                    showProgressDialog();
                    mPresenter.updateCommodity(id, Integer.valueOf(materialEditText.getText().toString().trim()), pos, alertDialog);
                } else {
                    return;
                }

            }
        });
    }

    @Override
    public void setBean(CommodityAndCategory category) {
        dissProgressDialog();
        if (categoryList == null) {
            this.categoryList = category.getCategory();
            categoryString = new ArrayList<>();
            categoryString.add("全部");
            for (Category category1 : categoryList) {
                categoryString.add(category1.getName());
            }
        }
        //正常刷新列表的显示
        addList(category.getCommodity());
    }

    @Override
    public void onDestroyView() {
        super.onDestroyView();
        unbinder.unbind();
    }

    @OnClick({R.id.classify_name, R.id.auto_orderby})
    public void onViewClicked(View view) {
        stringList.clear();
        if (popupWindow.isShowing()) {
            popupWindow.dismiss();
        }
        switch (view.getId()) {
            case R.id.classify_name:
                stringList.addAll(categoryString);
                popupWindow.showAsDropDown(classifyName);
                type = 0;
                break;
            case R.id.auto_orderby:
                stringList.addAll(sortString);
                popupWindow.showAsDropDown(autoOrderby);
                type = 1;
                break;
        }
    }

    @Override
    public void onLoadMoreRequested() {
        curpage++;
        if ("全部".equals(classifyName.getText().toString().trim())) {
            addData();
        } else {
            addDataByCategory();
        }
    }
}
